package com.tjetc.controller;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.tjetc.common.Result;
import com.tjetc.domain.Dclasses;
import com.tjetc.domain.Department;
import com.tjetc.domain.Doctor;
import com.tjetc.domain.Order;
import com.tjetc.service.DclassesService;
import com.tjetc.service.DepartmentService;
import com.tjetc.service.DoctorService;
import com.tjetc.service.OrderService;
import com.tjetc.service.impl.DclassesServiceImpl;
import com.tjetc.service.impl.DepartmentServiceImpl;
import com.tjetc.service.impl.DoctorServiceImpl;
import com.tjetc.service.impl.OrderServiceImpl;
import com.tjetc.utils.JwtUtil;
import com.tjetc.utils.PageInfo;

import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;
import java.io.IOException;
import java.lang.reflect.Method;
import java.time.DayOfWeek;
import java.time.LocalDate;
import java.time.format.TextStyle;
import java.util.List;
import java.util.Locale;
import java.util.UUID;

@WebServlet("/doctor/*")
@MultipartConfig(location = "D:\\yiyuanphoto")
public class DoctorServlet extends HttpServlet {
    private DoctorService doctorService = new DoctorServiceImpl();
    private DepartmentService departmentService=new DepartmentServiceImpl();
    private OrderService orderService=new OrderServiceImpl();
    private DclassesService dclassesService=new DclassesServiceImpl();
    @Override
    protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String uri = request.getRequestURI();
        String methodName = uri.substring(uri.lastIndexOf("/") + 1);
        try {
            Method method = this.getClass().getDeclaredMethod(methodName, HttpServletRequest.class, HttpServletResponse.class);
            method.invoke(this,request,response);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    protected void login(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        Doctor doctor = doctorService.login(username,password);
        String token= JwtUtil.createToken(username);
        if (doctor==null){
            new ObjectMapper().writeValue(response.getOutputStream(), Result.fail("用户名/密码错误"));
        }
        new ObjectMapper().writeValue(response.getOutputStream(), Result.success(token,"登录成功"));
    }

    protected void getDocInfoById(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        Integer did = Integer.valueOf(request.getParameter("did"));
        Doctor doctor = doctorService.getById(did);
        new ObjectMapper().writeValue(response.getOutputStream(), doctor);
    }

    protected void info(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String username = request.getParameter("username");
        Doctor doctor = doctorService.findByName(username);
        new ObjectMapper().writeValue(response.getOutputStream(), Result.success(doctor));
    }

    protected void listFifth(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        List<Doctor> doctors = doctorService.selectFifth();
        new ObjectMapper().writeValue(response.getOutputStream(),doctors);
    }

    protected void listDocByDepid(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        Integer depid = Integer.valueOf(request.getParameter("depid"));
        List<Doctor> doctors = doctorService.queryByDepid(depid);
        new ObjectMapper().writeValue(response.getOutputStream(),doctors);
    }

    protected void listAll(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        List<Doctor> doctors = doctorService.listAll();
        new ObjectMapper().writeValue(response.getOutputStream(),doctors);
    }

    protected void list(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String name = request.getParameter("name");
        String curPage = request.getParameter("curPage");
        String ps = request.getParameter("pageSize");
        name=name==null?"":name;
        //接受请求参数
        //空处理:赋值给当前页码
        int currentPage = curPage == null ? 1:Integer.valueOf(curPage);
        //每页显示的条数
        int pageSize = ps == null ? 5 : Integer.parseInt(ps);
        //总记录数
        int count = doctorService.getCount(name);
        PageInfo<Doctor> pageInfo = new PageInfo<>(currentPage, count, pageSize);
        List<Doctor> list=doctorService.list(name,pageInfo);
        pageInfo.setList(list);
        System.out.println("医生信息 = " + list);
        new ObjectMapper().writeValue(response.getOutputStream(),pageInfo);
    }


    protected void add(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String username=request.getParameter("username");
        int age=Integer.valueOf(request.getParameter("age"));
        String sex=request.getParameter("sex");
        String phone=request.getParameter("phone");
        int depid= Integer.valueOf(request.getParameter("depid"));
        Part part=request.getPart("photo");
        Doctor doctor=new Doctor();
        doctor.setUsername(username);
        doctor.setAge(age);
        doctor.setSex(sex);
        doctor.setPhone(phone);
        doctor.setDepid(depid);
        if (part!=null&&part.getSize()>0){
            String fn = part.getSubmittedFileName();
            String extName = fn.substring(fn.lastIndexOf("."));
            String fileName = UUID.randomUUID().toString()+extName;
            part.write(fileName);
            doctor.setAvatar("upload/"+fileName);
        }
        Doctor doctor1=doctorService.findByName(username);
        if(doctor1!=null){
            new ObjectMapper().writeValue(response.getOutputStream(), Result.fail("用户名重复"));
        }else{
        boolean b = doctorService.add(doctor);
        if (b){
            new ObjectMapper().writeValue(response.getOutputStream(), Result.success("添加成功"));
        }
        new ObjectMapper().writeValue(response.getOutputStream(), Result.fail("添加失败，出异常喽！"));
        }
    }


    protected void update(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        int id= Integer.parseInt(request.getParameter("id"));
        Doctor oldDoctor=doctorService.getById(id);
        String username=request.getParameter("username");
        int age=Integer.valueOf(request.getParameter("age"));
        String sex=request.getParameter("sex");
        String phone=request.getParameter("phone");
        int depid= Integer.valueOf(request.getParameter("depid"));
        Part part=request.getPart("photo");
        System.out.println("part = " + part);
        Doctor doctor=new Doctor();
        doctor.setId(id);
        doctor.setUsername(username);
        doctor.setAge(age);
        doctor.setSex(sex);
        doctor.setPhone(phone);
        doctor.setDepid(depid);
        if (part!=null&&part.getSize()>0 &&part.getSubmittedFileName()!=null){
            String fn = part.getSubmittedFileName();
            String extName = fn.substring(fn.lastIndexOf("."));
            String fileName = UUID.randomUUID().toString()+extName;
            part.write(fileName);
            doctor.setAvatar("upload/"+fileName);
        }else{
            doctor.setAvatar(oldDoctor.getAvatar());
        }
        boolean b = doctorService.update(doctor);
        if (b){
            new ObjectMapper().writeValue(response.getOutputStream(), Result.success("修改成功"));
        }
        new ObjectMapper().writeValue(response.getOutputStream(), Result.fail("修改失败"));
    }


    protected void del(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        int id= Integer.parseInt(request.getParameter("id"));
        Department department=departmentService.getByDid(id);
        if (department==null){
            Order order=orderService.findByDid(id);
            if (order==null){
                boolean b=doctorService.del(id);
                if (b){
                    new ObjectMapper().writeValue(response.getOutputStream(), Result.success("删除成功"));
                }
                new ObjectMapper().writeValue(response.getOutputStream(), Result.fail("删除失败"));
            }else{
                new ObjectMapper().writeValue(response.getOutputStream(), Result.fail("删除失败,当前医生有相关的预约信息"));
            }

        }else{
            new ObjectMapper().writeValue(response.getOutputStream(),Result.fail("该医生是主任医师不能删除"));
        }
    }

    protected void findPasswordById(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        int id= Integer.parseInt(request.getParameter("id"));
        System.out.println("id = " + id);
        Doctor doctor=doctorService.getpwdById(id);
        String password=doctor.getPassword();
        new ObjectMapper().writeValue(response.getOutputStream(),password);

    }


    protected void updatepwd(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        int id= Integer.parseInt(request.getParameter("id"));
        String password=request.getParameter("newPassword");
        Doctor doctor=new Doctor();
        doctor.setId(id);
        doctor.setPassword(password);
        boolean b=doctorService.updatepwd(doctor);
        if (b){
            new ObjectMapper().writeValue(response.getOutputStream(), Result.success("修改成功"));
        }
        new ObjectMapper().writeValue(response.getOutputStream(), Result.fail("修改失败"));
    }

    protected void qiandao(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //医生id
        int id= Integer.parseInt(request.getParameter("id"));
        // 获取当前日期
        LocalDate today = LocalDate.now();
        // 获取今天的星期
        DayOfWeek dayOfWeek = today.getDayOfWeek();
        // 获取星期的本地化名称
        String dayOfWeekName = dayOfWeek.getDisplayName(TextStyle.FULL, Locale.getDefault());
        if (dayOfWeekName.equals("星期一")){
            dayOfWeekName="周一";
        }else if (dayOfWeekName.equals("星期二")){
            dayOfWeekName="周二";
        }
        else if (dayOfWeekName.equals("星期三")){
            dayOfWeekName="周三";
        }
        else if (dayOfWeekName.equals("星期四")){
            dayOfWeekName="周四";
        }
        else if (dayOfWeekName.equals("星期五")){
            dayOfWeekName="周五";
        }
        else if (dayOfWeekName.equals("星期六")){
            dayOfWeekName="周六";
        }
        else if (dayOfWeekName.equals("星期日")){
            dayOfWeekName="周日";
        }
        //System.out.println("dayOfWeekName = " + dayOfWeekName);
        Dclasses dclasses=dclassesService.findByIdandDate(id,dayOfWeekName);
        new ObjectMapper().writeValue(response.getOutputStream(), dclasses);
    }


    protected void sureqiandao(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //医生id
        int id= Integer.parseInt(request.getParameter("id"));
        // 获取当前日期
        LocalDate today = LocalDate.now();
        // 获取今天的星期
        DayOfWeek dayOfWeek = today.getDayOfWeek();
        // 获取星期的本地化名称
        String dayOfWeekName = dayOfWeek.getDisplayName(TextStyle.FULL, Locale.getDefault());
        if (dayOfWeekName.equals("星期一")){
            dayOfWeekName="周一";
        }else if (dayOfWeekName.equals("星期二")){
            dayOfWeekName="周二";
        }
        else if (dayOfWeekName.equals("星期三")){
            dayOfWeekName="周三";
        }
        else if (dayOfWeekName.equals("星期四")){
            dayOfWeekName="周四";
        }
        else if (dayOfWeekName.equals("星期五")){
            dayOfWeekName="周五";
        }
        else if (dayOfWeekName.equals("星期六")){
            dayOfWeekName="周六";
        }
        else if (dayOfWeekName.equals("星期日")){
            dayOfWeekName="周日";
        }
        //System.out.println("dayOfWeekName = " + dayOfWeekName);
        Dclasses dclasses1=dclassesService.findByIdandDate(id,dayOfWeekName);
        Dclasses dclasses=new Dclasses();
        dclasses.setId(dclasses1.getId());
        dclasses.setStatus(1);
        boolean b=dclassesService.setqiandao(dclasses);
        if (b){
            new ObjectMapper().writeValue(response.getOutputStream(), Result.success("签到成功"));
        }
        new ObjectMapper().writeValue(response.getOutputStream(), Result.fail("签到失败"));
    }


}
